package com.dewod.producesales;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dewod.producesales.activity.ValidateActivity;
import com.dewod.producesales.activity.setting.NetRequestSettingActivity;
import com.dewod.producesales.activity.DeliverActivity;
import com.dewod.producesales.activity.setting.SettingCenterActivity;
import com.dewod.producesales.model.view.RequestSetting;
import com.dewod.producesales.service.RegisterService;
import com.dewod.producesales.utils.SharedUtil;
import com.dewod.producesales.utils.common.TtsManager;
import com.dewod.producesales.utils.request.RequestApiUtil;
import com.dewod.producesales.utils.request.RequestBaseUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private final List<Button> modes = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        modes.add(findViewById(R.id.btn_prepare));
        this.findViewById(R.id.btn_prepare).setOnClickListener(v -> {
            // 跳转到ValidateActivity
            Intent intent = new Intent(MainActivity.this, ValidateActivity.class);
            startActivity(intent);
        });

        modes.add(findViewById(R.id.btn_deliver));
        this.findViewById(R.id.btn_deliver).setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, DeliverActivity.class);
            startActivity(intent);
        });

        initMode();

        this.findViewById(R.id.btn_setting).setOnClickListener(v -> {
            // 创建输入框
            EditText input = new EditText(this);
            input.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD);

            new AlertDialog.Builder(this)
                .setTitle("请输入管理员密码")
                .setView(input)
                .setPositiveButton("确认", (dialog, which) -> {
                    String password = input.getText().toString();
                    if ("159753".equals(password)) {
                        // 密码正确，跳转设置页面
                        Intent intent = new Intent(MainActivity.this, SettingCenterActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(MainActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", (dialog, which) -> {})
                .show();
        });

        // 初始化TTS
        TtsManager.getInstance().init(getApplicationContext());

        // 初始化请求设置
        String requestSetting_str = SharedUtil.getInstance(this).readString(RequestSetting.KEY_REQUEST, GsonUtils.toJson(RequestSetting.init()));
        RequestSetting requestSetting = GsonUtils.fromJson(requestSetting_str, RequestSetting.class);
        RequestBaseUtil.baseUrl = requestSetting.getUrl();

        // PDA设备注册到服务端
        RegisterService.register(RequestBaseUtil.baseUrl, success -> {
            if (success) {
                // 注册成功逻辑
                ToastUtils.showLong("设备注册成功");
            } else {
                // 注册失败逻辑
                ToastUtils.showLong("设备注册失败");
                try {
                    Thread.sleep(1000);
                    Intent intent = new Intent(this, NetRequestSettingActivity.class);
                    startActivity(intent);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        LocalBroadcastManager.getInstance(this)
                .registerReceiver(updateReceiver, new IntentFilter("WORK_MODE_CHANGE"));
    }

    private final BroadcastReceiver updateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("updateReceiver", "收到数据更新广播");
            initMode(); // 执行刷新逻辑
        }
    };

    private void initMode() {
        String[] workModes = getResources().getStringArray(R.array.workMode);
        List<String> workModeList = Arrays.asList(workModes);
        String mode = SharedUtil.getInstance(this).readString("WORK_MODE", workModes[0]);
        int index = workModeList.indexOf(mode);
        for (int i = 0 ; i < modes.size(); i++ ) {
            modes.get(i).setVisibility(i == index ? View.VISIBLE : View.GONE);
        }
    }

}